package com.lwl.mini.binding;

import com.lwl.mini.builder.annotation.Delete;
import com.lwl.mini.builder.annotation.Insert;
import com.lwl.mini.builder.annotation.Select;
import com.lwl.mini.builder.annotation.Update;
import com.lwl.mini.mapping.SqlCommandType;
import lombok.Data;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;


/**
 * @author lwl
 * @create 2022/4/13 13:24
 */
public class SQLInfo {

    //Sql信息
    private final SqlCommand sqlCommand = new SqlCommand();

    public SQLInfo evalMethod(Method method) {
        String sql = null;
        SqlCommandType type = null;
        //默认取方法中的第一个注释
        Annotation annotation = method.getAnnotations()[0];
        if (annotation instanceof Select) {
            Select select = (Select) annotation;
            sql = parseSql(select.value()[0]);
            type = SqlCommandType.SELECT;
        }
        if (annotation instanceof Update) {
            Update update = (Update) annotation;
            sql = parseSql(update.value()[0]);
            type = SqlCommandType.UPDATE;
        }
        if (annotation instanceof Delete) {
            Delete delete = (Delete) annotation;
            sql = parseSql(delete.value()[0]);
            type = SqlCommandType.DELETE;
        }
        if (annotation instanceof Insert) {
            Insert insert = (Insert) annotation;
            sql = parseSql(insert.value()[0]);
            type = SqlCommandType.INSERT;
        }
        if(sql != null){
            sqlCommand.setSql(sql);
            sqlCommand.setType(type);
        } else {
          throw new BindingException("获取类中方法信息出错,该方法为:"+method);
        }
        return this;
    }

    private String parseSql(String str) {
        return str.replace('[', ' ').replace(']', ' ');
    }

    public SqlCommandType getType(){
        return sqlCommand.getType();
    }

    public String getSQL(){
        return sqlCommand.getSql();
    }

    @Data
    public static class SqlCommand {
        String sql;
        SqlCommandType type;
    }
}
